#coding=utf-8

import os.path

def _check_files(files):
    useful_files = []
    for f in files:
        if f.endswith('.xls') or f.endswith('.xlsx'):
            useful_files.append(f)
    return useful_files

def _read_matches(matches_file):

    fo = open(matches_file)
    originName_newName_matches =  {}
    for line in fo:
        line = line.strip()
        if not line:
            continue
        l = line.split()
        if len(l) != 2:
            continue
        originName = l[0]
        newName = l[1]
        originName_newName_matches[originName] = newName
    fo.close()
    return originName_newName_matches

def _search_usefule_files(usefule_files, subStr):
    #如果文件 修改对应的文件名
    for f in usefule_files:
        if subStr in f:
            return f
    return None

def change_file_name(files_dir,mathches):

    if not os.path.isdir(files_dir):
        print 'files_dir 非文件目录'
    for root, dirs, files in os.walk(files_dir):
        print 'root_dir:%s' % root

        #如果是目录递归
        for sub_dir in dirs:
            change_file_name(sub_dir, mathches)

        usefule_files = _check_files(files)

        if len(usefule_files) > 0:
            for key, value in mathches.items():
                aimed_file = _search_usefule_files(usefule_files, key)
                if aimed_file:
                    value = value + "." + aimed_file.split(".")[1]
                    aimed_file = os.path.join(files_dir, aimed_file)
                    value = os.path.join(files_dir, value)
                    # print aimed_file, value
                    os.rename(aimed_file, value)
    print "#####   ChangeNames successfully #####"

if __name__ == '__main__':
    files_dir = 'excels'
    matches_file = 'file_name_matches.txt'
    name_matches = _read_matches(matches_file)
    change_file_name(files_dir, name_matches)
